package imgshare.common.exception;

import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import com.google.common.base.VerifyException;
import imgshare.common.api.CommonResult;
import imgshare.common.api.ResultCode;
import io.jsonwebtoken.JwtException;
import org.apache.shiro.ShiroException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MultipartException;

import java.util.List;

/**
 * 全局异常处理
 */
@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final Log log = LogFactory.get();

    @ExceptionHandler(JwtException.class)
    public CommonResult<?> handle(JwtException e) {
        log.warn(e.getCause().getMessage());
        return CommonResult.failed(ResultCode.UNAUTHORIZED);
    }

    @ExceptionHandler(UnauthorizedException.class)
    public CommonResult<?> handle(UnauthorizedException e) {
        return CommonResult.failed(ResultCode.FORBIDDEN);
    }

    @ExceptionHandler(ShiroException.class)
    public CommonResult<?> handle(ShiroException e) {
        return CommonResult.failed(ResultCode.UNAUTHORIZED);
    }

    @ExceptionHandler(value = ApiException.class)
    public CommonResult<?> handle(ApiException e) {
        if (e.getErrorCode() != null) {
            return CommonResult.failed(e.getErrorCode());
        }
        return CommonResult.failed(e.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public CommonResult<?> handle(MethodArgumentNotValidException e) {
        StringBuilder message = new StringBuilder();
        List<ObjectError> allErrors = e.getBindingResult().getAllErrors();
        for(ObjectError error : allErrors) {
            message.append(error.getDefaultMessage()).append(",");
        }
        String s = message.substring(0, message.length()-1);
        return CommonResult.validateFailed(s);
    }

    @ExceptionHandler(VerifyException.class)
    public CommonResult<?> handle(VerifyException e) {
        return CommonResult.failed(e.getMessage());
    }

    @ExceptionHandler(MultipartException.class)
    public CommonResult<?> handle(MultipartException e) {
        return CommonResult.failed(e.getCause().getMessage());
    }
}
